package com.c4p.im.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.c4p.im.session.ISessionStore;
import com.c4p.im.session.IUserChannelStore;
import com.c4p.im.session.IUserNetStore;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.time.Instant;

@Slf4j
@ChannelHandler.Sharable
public class MessageHandler extends SimpleChannelInboundHandler<Object> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("receive msg {}", msg);

        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(Instant.now().toEpochMilli() + ":" + "receive msg");
        ctx.writeAndFlush(textWebSocketFrame);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //移除连接
        ISessionStore sessionStore = SpringUtil.getBean(ISessionStore.class);
        sessionStore.remove(ctx.channel());
        log.info("sessionStore channel remove");

        String userId = ctx.channel().attr(UserInfoExactHandler.USER_INFO_ATTRIBUTEKEY).get();
        IUserChannelStore userChannelStore = SpringUtil.getBean(IUserChannelStore.class);
        userChannelStore.remove(userId);
        log.info("userChannelStore: {} remove", userId);

        IUserNetStore userNetStore = SpringUtil.getBean(IUserNetStore.class);
        userNetStore.remove(userId);
        log.info("userNetStore: {} remove", userId);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof String){
            log.info("token : {}", evt);
        }
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            //加入连接， 1，连接存在哪？
            ISessionStore sessionStore = SpringUtil.getBean(ISessionStore.class);
            sessionStore.add(ctx.channel());
            log.info("sessionStore channel add");

            String userId = ctx.channel().attr(UserInfoExactHandler.USER_INFO_ATTRIBUTEKEY).get();
            IUserChannelStore userChannelStore = SpringUtil.getBean(IUserChannelStore.class);
            userChannelStore.put(userId, ctx.channel());
            log.info("userChannelStore add");

            IUserNetStore userNetStore = SpringUtil.getBean(IUserNetStore.class);
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            Environment environment = SpringUtil.getBean(Environment.class);
            String port = environment.getProperty("server.port");
            userNetStore.put(userId, hostAddress, port);
            log.info("userNetStore add: {}, ip: {}, port:{}" , userId, hostAddress, port);

        }

        super.userEventTriggered(ctx, evt);
    }


}
